package twitterbot;

import static twitterbot.constant.Constants.ID;
import static twitterbot.constant.Constants.SEARCH_WORD;
import static twitterbot.constant.Constants.PASS;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitterbot.entity.TwitterBeans;

@SuppressWarnings("serial")
public class GaeTwitterBotServlet extends HttpServlet {
	public static String MUSISURU_WORD = "android_bot_t";

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		ArrayList<TwitterBeans> list = search(SEARCH_WORD);
		for (TwitterBeans bean : list) {
			if (!bean.getUserName().equals(ID)) {
				say("[" + bean.getUserName() + "] " + bean.getTubuyaki());
				System.out.println(bean.getUserName());
				System.out.println(bean.getTubuyaki());
				
			}
		}
	}

	/**
	 * 指定したワードを検索し、TwitterBeansリストを返す
	 * 
	 * @param input
	 * @return
	 */
	public ArrayList<TwitterBeans> search(String input) {

		Twitter twitter = new Twitter();
		Query query = new Query(input);
		QueryResult result;
		ArrayList<TwitterBeans> listTwitter = new ArrayList<TwitterBeans>();
		try {
			result = twitter.search(query);
			for (Tweet tweet : result.getTweets()) {
				if (!tweet.getFromUser().equals(MUSISURU_WORD)) {
					TwitterBeans bean = new TwitterBeans();
					setBeansData(bean, tweet);
					listTwitter.add(bean);
				}
			}
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		return listTwitter;
	}

	/**
	 * 指定した文字をつぶやく
	 * 
	 * @param input
	 * @return
	 */
	private void say(String input) {
		try {
			Twitter twitter = new Twitter(ID, PASS);
			twitter.updateStatus(input);
		} catch (TwitterException e) {
			e.printStackTrace();
		}
	}

	/**
	 * TweetオブジェクトからTwitterBeansを作成する
	 * 
	 * @param bean
	 * @param tweet
	 */
	private void setBeansData(TwitterBeans bean, Tweet tweet) {
		bean.setUserName(tweet.getFromUser());
		bean.setProfileImageURL(tweet.getProfileImageUrl());
		bean.setTubuyaki(tweet.getText());
		bean.setTubuyakiTime(tweet.getCreatedAt().toString());
	}

}
